<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜品名称"
          clearable
          @input="handleQuery"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dish:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dish:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="multiple"
          size="mini"
          @click="handleStatus(1)"
        >批量起售</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          size="mini"
          @click="handleStatus(0)"
        >批量停售</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="菜品名称" align="center" prop="name" />
      <el-table-column label="菜品分类" align="center" prop="categoryName" />
      <el-table-column label="售价" align="center" prop="price" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="售卖状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0">停售</el-tag>
          <el-tag v-else>在售</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dish:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dish:remove']"
          >删除</el-button>

          <el-button
            v-if="scope.row.status==0"
            size="small"
            type="success"
            @click="handleStatus(1,scope.row)"
          >在售</el-button>
          <el-button
            v-else
            size="small"
            type="danger"
            @click="handleStatus(0,scope.row)"
          >停售</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="form.categoryName" placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入菜品价格" />
        </el-form-item>

        <el-form-item label="口味配置">
          <el-button type="primary" @click="show" icon="el-icon-plus" :disabled="form.dishFlavors.length==4?true:false">添加配置</el-button>
          <el-card v-show="isShow" class="box-card">
            <el-tag type="info">口味名(三个字)口味标签</el-tag>
            <div
            v-for="(items,index) in form.dishFlavors"
            :key="index">
              <el-select v-model="items.name" placeholder="请选择" value-key="value" @change="(value)=>change(value,index)">
                <el-option
                        v-for="item in flavors"
                        :key="item.name"
                        :label="item.name"
                        :value="item"
                        v-show="items.name == item.name ||!form.selectIdsArr.includes(item.name)"
                ></el-option>
              </el-select>
              <el-tag
                v-if="form.dishFlavors[index].value!=[]"
                v-for="tagflavor in form.dishFlavors[index].value"
                :key="tagflavor"
                closable
                @close="handleClose(tagflavor,index)"
              >
                {{tagflavor}}
              </el-tag>
              <el-button  type="danger" icon="el-icon-delete" circle @click="deleteFlavor(index)"></el-button>
            </div>
          </el-card>
        </el-form-item>

        <el-form-item label="图片">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDish, getDish, delDish, addDish, updateDish ,updateStatusDish} from "@/api/system/dish";
import { listCategory, getCategory } from "@/api/system/category";
export default {
  name: "Dish",
  data() {
    return {
      categoryList: [],
      isShow: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品管理表格数据
      dishList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      flavors: [
        {name: "甜味", value: ["无糖", "少糖", "半糖", "多糖", "全糖"]},
        {name: "温度", value: ["热饮", "常温", "去冰", "少冰", "多冰"]},
        {name: "忌口", value: ["不要葱", "不要蒜", "不要香菜", "不要辣"]},
        {name: "辣度", value: ["不辣", "微辣", "中辣", "重辣"]}
      ],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form : {
        id: null,
        name: null,
        categoryId: null,
        categoryName: null,
        price: null,
        code: null,
        image: null,
        description: null,
        status: 0,
        sort: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        isDeleted: null,
        dishFlavors: [],
        selectIdsArr: []
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "菜品名称不能为空", trigger: "blur"}
        ],
        categoryName: [
          {required: true, message: "菜品分类不能为空", trigger: "blur"}
        ],
        image: [
          {required: true, message: "图片不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "0 停售 1 起售不能为空", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "顺序不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        createUser: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        isDeleted: [
          {required: true, message: "是否删除不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.reset();
    this.getList();
    this.getCategoryList();
  },
  methods: {
    /** 查询菜品及套餐分类列表 */
    getCategoryList() {
      this.loading = true;
      listCategory({type:1}).then(response => {
        this.categoryList = response.rows;
        this.loading = false;
      });
    },
    deleteFlavor(index) {
      let flavorKey = this.form.dishFlavors;
      flavorKey.splice(index, 1);

      this.form.selectIdsArr = [];
      for (const flavorKeyElement of flavorKey) {
        this.form.selectIdsArr.push(flavorKeyElement.name);
      }
      if (flavorKey.length==0){
        this.isShow = false;
      }
    },

    handleClose(tag, index) {
      let tags = this.form.dishFlavors[index];
      for (const dishfKey of tags.value) {
        if (dishfKey == tag){
          tags.value.splice(tags.value.indexOf(tag),1)
        }
      }
      if (tags.value.length==0) {
        this.deleteFlavor(index)
      }
    },

    show() {
      this.isShow = true;
      this.form.dishFlavors.push({"name":"","value":[]})
    },

    change(obj,index) {
      //初始化
      this.flavors = [
        {name: "甜味", value: ["无糖", "少糖", "半糖", "多糖", "全糖"]},
        {name: "温度", value: ["热饮", "常温", "去冰", "少冰", "多冰"]},
        {name: "忌口", value: ["不要葱", "不要蒜", "不要香菜", "不要辣"]},
        {name: "辣度", value: ["不辣", "微辣", "中辣", "重辣"]}
      ];
      this.form.dishFlavors[index] = obj;
      this.form.selectIdsArr = [];
      for (const item of this.form.dishFlavors){
          if (item.name){
            this.form.selectIdsArr.push(item.name);
          }
      }
    },


    /** 查询菜品管理列表 */
    getList() {
      this.loading = true;
      listDish(this.queryParams).then(response => {
        this.dishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        categoryId: null,
        categoryName: null,
        price: null,
        code: null,
        image: null,
        description: null,
        status: 0,
        sort: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        isDeleted: null,
        dishFlavors: [],
        selectIdsArr: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryList();
      this.open = true;
      this.title = "添加菜品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getCategoryList();
      const id = row.id || this.ids
      getDish(id).then(response => {
        this.form = response.data;
        this.isShow = true;
        this.form.selectIdsArr = [];
        this.open = true;
        this.title = "修改菜品管理";
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.categoryIsNum(this.form.categoryName);
          if (this.form.id != null) {
            console.log(this.form);
            updateDish(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.categoryIsNum(this.form.categoryName);
            addDish(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    categoryIsNum(categoryName) {
      var pattern = /^[0-9]/;
      if (pattern.test(categoryName)){
        this.form.categoryId = categoryName;
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除菜品管理编号为"' + ids + '"的数据项？').then(function() {
        return delDish(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleStatus(status,row) {
      let ids = this.ids;
      if (row){
        ids = row.id || this.ids;
      }
      this.$modal.confirm('是否确认'+status ==0?'起售':'停售'+'菜品编号为"' + ids + '"的数据项？').then(function() {
        return updateStatusDish(ids,status);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("修改状态成功！");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dish/export', {
        ...this.queryParams
      }, `dish_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
